/**
 * 该场景固定长宽: 1920 x 1080
 * 
 * HTML 设置方案
 * #main
 *   #panel (底层, 1920x1080, zrender)
 *   #desk
 *   #titleFrame
 *   #desk
 * 
 * init param
 *   可以选择刚开始 desk 部分在左边还是右边. 左边是 style=left, 右边是 style=right
 */
import layout from '../compute/v1/layout';

import events from '../compute/v1/events';
import { Panel } from '../view/v1/panel';

function createScene(context) {
	let t = new App(context);
	global.app = t;
	let scene = new context.Scene({
		require : ['zrender'],
		init : (libs) => t.init(libs),
		destroy : () => t.destroy(),
		collectInfo : () => t.collectInfo(),
		onMessage : (key, data) => t.onMessage(key, data),
	});
	t.sendStatus = scene.sendStatus;
	return scene;
};

class App {
	constructor(context) {
		this.context = context;
	}
	style = {
		left : true
	};

	init(libs) {
		this.handleInitParam();

		// 新的部分
		this.panel = new Panel({
			context : this.context,
			zrender : libs.zrender
		});
		this.panel.on(events.STATUS_REPORT_TO_SERVER, () => this.sendStatus());
		this.panel._init();
	}

	sendStatus() {
		// need to override
	}

	handleInitParam() {
		/** @type {string} */ const style = this.context.parseInitParam().style;
		if (style) {
			switch (style) {
				case 'left':
					layout.config.setDestLeft(true);
					this.style.left = true;
					break;
				case 'right':
					layout.config.setDestLeft(false);
					this.style.left = false;
					break;
				default: break;
			}
		}
	}
	
	/*
	 * 收集状态数据
	 */
	collectInfo() {
		const obj = {
			style : this.style,
			version : '0.5.20230530',
		};

		const context = this.panel.getContext();
		if (context.animation) {
			obj.icons = context.animation.icons;
			obj.iconIndex = context.animation.index;
		}

		return obj;
	}
	
	/* **********
	 * 状态控制 *
	 ********** */

	onMessage (name, arg) {
		switch (name) {
			case 'style-update': {
				typeof(arg.style) === 'string' && this.onStyleUpdated(arg.style);
				this.sendStatus();
			} return;
		}
		console.log("bottom 收到命令: " + name);
		console.log(arg);
	}

	onStyleUpdated(style) {
		if (this.style.left && style === 'right') {
			layout.config.setDestLeft(false);
			this.style.left = false;
			this.panel.emit(events.STYLE_LR_UPDATED, {old: 'left', new: 'right'});
		} else if (!this.style.left && style === 'left') {
			layout.config.setDestLeft(true);
			this.style.left = true;
			this.panel.emit(events.STYLE_LR_UPDATED, {old: 'right', new: 'left'});
		}
	}
}

export default createScene;
